package com.example.jdbc.client;

import java.sql.*;
import java.util.Properties;
import java.util.logging.Logger;

public class JdbcProxyDriver implements Driver {
    private static final String URL_PREFIX = "jdbc:proxy:";
    private static final String DEFAULT_SERVER = "http://localhost:8080";

    static {
        try {
            DriverManager.registerDriver(new JdbcProxyDriver());
        } catch (SQLException e) {
            throw new RuntimeException("Failed to register JDBC proxy driver", e);
        }
    }

    @Override
    public Connection connect(String url, Properties info) throws SQLException {
        if (!acceptsURL(url)) {
            return null;
        }

        String serverUrl = extractServerUrl(url);
        return new JdbcProxyConnection(serverUrl, info);
    }

    @Override
    public boolean acceptsURL(String url) throws SQLException {
        return url != null && url.startsWith(URL_PREFIX);
    }

    @Override
    public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException {
        return new DriverPropertyInfo[0];
    }

    @Override
    public int getMajorVersion() {
        return 1;
    }

    @Override
    public int getMinorVersion() {
        return 0;
    }

    @Override
    public boolean jdbcCompliant() {
        return false;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        throw new SQLFeatureNotSupportedException();
    }

    private String extractServerUrl(String jdbcUrl) {
        String url = jdbcUrl.substring(URL_PREFIX.length());
        return url.isEmpty() ? DEFAULT_SERVER : url;
    }
}